package zh.dummy.netty.server.handler;

import java.net.InetSocketAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import zh.dummy.netty.core.protocol.ErrorType;
import zh.dummy.netty.core.protocol.MessageType;
import zh.dummy.netty.core.protocol.NettyMessage;
import zh.dummy.netty.server.util.NettyMessageBuilder;
import zh.dummy.netty.server.util.NettyUtil;

public class LoginAuthRespHandler extends ChannelHandlerAdapter {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	public void channelRead(ChannelHandlerContext ctx, Object msg){
		NettyMessage message = (NettyMessage)msg;
		Channel channel = ctx.channel();
		//如果是握手请求消息，处理，其他消息透传
		if(message.getHeader() != null
			&& message.getHeader().getType() == MessageType.LOGIN_REQ.value()){
			if(logger.isDebugEnabled()){
				logger.debug("received login request");
			}
			String id = getId(message,channel);
			NettyMessage loginResp = null;
			//重复登录，拒绝
			if(isLogin(id)){
				loginResp = NettyMessageBuilder.buildAuthResp(id,ErrorType.REPEATED_LOGIN);
			}else{
				boolean isOK = safeValidation();
				loginResp = isOK ? NettyMessageBuilder.buildAuthResp(id,ErrorType.SUCCESS):NettyMessageBuilder.buildAuthResp(id,ErrorType.ILLEGAL_LOGIN);
				if(isOK){
					if(logger.isInfoEnabled()){
						logger.info("auth success register : "+id);
					}
					registerChannel(id, ctx.channel());
				}
			}
			if(logger.isDebugEnabled()){
				logger.debug("The login response is : "+loginResp.getBody().toString());
			}
			ctx.writeAndFlush(loginResp);
		}else{
			ctx.fireChannelRead(msg);
		}
	}
	

	
	protected boolean safeValidation() {
		// TODO Auto-generated method stub
		return true;
	}



	private boolean isLogin(String id) {
		return NettyUtil.containsChannel(id);
	}



	private String getId(NettyMessage message,Channel channel) {
		String id = null;
		if(message.getBody() != null && message.getBody().get("id") != null){
			id = String.valueOf(message.getBody().get("id"));
		}else{
			InetSocketAddress address = (InetSocketAddress) channel.remoteAddress();
			String ip = address.getAddress().getHostAddress();
			id = ip;
		}
		return id;
	}



	private void registerChannel(String id, Channel channel) {
		NettyUtil.putChannel(id, channel);
	}


	public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause){
		ctx.close();
		ctx.fireExceptionCaught(cause);
	}
}
